using System;
using System.Linq.Expressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Close.io.API
{
	public class CloseIoUpdateBuilder<TObject> : Builder
	{
		private CloseIoUpdateBuilder _builder;

		public CloseIoUpdateBuilder()
		{
			_builder = new CloseIoUpdateBuilder();
		}

		public CloseIoUpdateBuilder<TObject> Add<TMember>(Expression<Func<TObject, TMember>> expression, TMember value)
		{

			var memberExpression = (MemberExpression)expression.Body;
			var propertyName = memberExpression.Member.Name;
			var fieldName = GetJsonFieldName(typeof(TObject), propertyName);

			var property = new JProperty(fieldName, value);

			_builder = _builder.Add(property);

			return this;
		}

		public CloseIoUpdateBuilder<TObject> AddCustomFieldUpdate(string fieldName, object value)
		{

			if (!fieldName.StartsWith("custom."))
			{
				fieldName = "custom." + fieldName;
			}

			var property = new JProperty(fieldName, value);

			_builder = _builder.Add(property);

			return this;
		}

		public string GetUpdateJson()
		{
			return _builder.UpdateJObject.ToString(Formatting.None);
		}
	}

	public class CloseIoUpdateBuilder
	{
		private readonly JObject _updateJObject = new JObject();

		public JObject UpdateJObject
		{
			get { return _updateJObject; }
		}


		public CloseIoUpdateBuilder Add(JProperty property)
		{

			UpdateJObject.Add(property);

			return this;
		}
	}
}